package com.ghsc.ghxc.jsb.ui.integral.activity

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import android.telephony.TelephonyManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.library.shape.ShapeTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.afterTextChangeListener
import com.cn.appcore.ext.dp
import com.cn.appcore.ext.load
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.transformRoundCorner
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.dingtalk.mars.comm.PlatformComm.context
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityIntegralCommodityDetailBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ext.setOnFastClickListener
import com.ghsc.ghxc.jsb.ext.showCustomPopup
import com.ghsc.ghxc.jsb.ext.textString
import com.ghsc.ghxc.jsb.ui.home.adapter.CommodityDetailBannerAdapter
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.bean.IntegralGoodsDetailsBean
import com.ghsc.ghxc.jsb.ui.integral.bean.IntegralSkuBean
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.library.flowlayout.FlowLayoutManager
import com.library.flowlayout.SpaceItemDecoration
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.util.KeyboardUtils
import com.youth.banner.indicator.CircleIndicator


/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.activity
 * 类名：IntegralGoodsDetailActivity
 * 创建时间：2024/5/21 17:20
 * 创建人 @author： xiaolin
 * 描述 ：Todo...商品详情
 */
class IntegralGoodsDetailActivity  : BaseVMActivity<IntegralSupermarketViewModel, ActivityIntegralCommodityDetailBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_integral_commodity_detail
    }

    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
        return IntegralSupermarketViewModel::class.java
    }
    private val pid: String? by intentExtras("pid", "0")
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }


    var commodityDetailBean : IntegralGoodsDetailsBean?=null

    private val mAdapter by lazy { ListPicAdapter() }
    var mList = arrayListOf<String>()
    override fun initView() {

        binding.rvList.isNestedScrollingEnabled = false
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.replaceData(mList)

        val map: HashMap<String, Any> = HashMap()
        map["pid"] =pid.toString()
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.ontGoodsDetailDataMethod(it1) }
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnMain.setSingleClickListener {
            commodityDetailBean?.let {
                RouterUtils.startToJumpSingleChat(this,it.uid)
            }
        }
        binding.llBtnPhone.setSingleClickListener {
            //拨打电话 跳转拨号界面
            commodityDetailBean?.let {
                val myCallIntent = Intent()
                myCallIntent.action = Intent.ACTION_DIAL
                myCallIntent.data = Uri.parse("tel:" + it.mobile)
                startActivity(myCallIntent)
            }
        }
        binding.tvCommoditySpecification.setOnFastClickListener {
            //商品规格
            val map: HashMap<String, Any> = HashMap()
            map["pid"] = pid.toString()
            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSkuDetailMethod(it1) }
        }
        binding.sllBuy.setSingleClickListener {
            //商品规格
            val map: HashMap<String, Any> = HashMap()
            map["pid"] = pid.toString()
            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSkuDetailMethod(it1) }
        }
        binding.rlClose.setOnFastClickListener {
            finish()
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@IntegralGoodsDetailActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@IntegralGoodsDetailActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            ontGoodsDetailData.observe(this@IntegralGoodsDetailActivity) {
                //详情
                it.data.data.let {
                    commodityDetailBean = it
                    val bannerList = it.images.split(",")
//                    if (bannerList.isNotEmpty()) {
//                        it.img = bannerList[0]
//                    }
                    //设置banner
                    binding.banner.setAdapter(CommodityDetailBannerAdapter(bannerList))
                        .addBannerLifecycleObserver(this@IntegralGoodsDetailActivity)
                        .indicator = CircleIndicator(this@IntegralGoodsDetailActivity)
                    binding.tvCommodityName.text = it.title

                    mAdapter.replaceData(bannerList)


                }
            }
            onSkuDetailData.observe(this@IntegralGoodsDetailActivity){
                //规格
                if(it.data.list.isNotEmpty()){
                    val commoditySpecPopup =
                        CommoditySpecPopup(this@IntegralGoodsDetailActivity,
                            it.data.list.toMutableList()
                        )
                    commoditySpecPopup.apply {
                        showCustomPopup(this, builder = {
                            autoFocusEditText(false)
                        })
                    }
                }else{
                    showToast("该商品暂无规格~")
                }
            }

        }
    }

    inner class CommoditySpecPopup(context: Context, list: MutableList<IntegralSkuBean>) : BottomPopupView(context) {
        private val mContext = context
        var skuList=list
        var skuItemBean:IntegralSkuBean?=null
        private var ivCommodityImg: ImageView? = null
        private var tvCommodityName: TextView? = null
        private var stock: TextView? = null
        private var skuprice: TextView? = null
        private var price: TextView? = null
        private  var etCount: EditText? = null

        private var buyCount = 1

        override fun getImplLayoutId() = R.layout.popup_commodity_integral_spec




        override fun onCreate() {
            super.onCreate()
            skuItemBean=skuList[0]
            skuList[0].isSelected=true
            ivCommodityImg = findViewById(R.id.ivCommodityImg)
            tvCommodityName = findViewById(R.id.tvCommodityName)
            stock= findViewById(R.id.stock)
            skuprice= findViewById(R.id.skuprice)
            price= findViewById(R.id.price)

            val ivDelete = findViewById<ImageView>(R.id.ivDelete)
            etCount = findViewById(R.id.etCount)
            val ivAdd = findViewById<ImageView>(R.id.ivAdd)
            val rvList = findViewById<RecyclerView>(R.id.rvList)

            skuItemBean?.let {
                ivCommodityImg?.load(it.images, builder = {
                    transform(transformRoundCorner(10))
                })
                tvCommodityName!!.text=it.skuname

                skuprice!!.text=it.skuprice.toString()
                price!!.text=it.price.toString()
                stock!!.text="库存: "+it.stock
                price!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            }
            buyCount = etCount!!.textString.trim().toInt()
            ivDelete.setOnClickListener {
                if (buyCount <= 1) return@setOnClickListener
                buyCount--
                etCount!!.setText("$buyCount")
                KeyboardUtils.hideSoftInput(this)
            }
            ivAdd.setOnClickListener {
                if (buyCount >= 99) return@setOnClickListener
                buyCount++
                etCount!!.setText("$buyCount")
                KeyboardUtils.hideSoftInput(this)
            }
            etCount!!.afterTextChangeListener {
                if (it.isNotEmpty()) {
                    buyCount = it.toInt()
                    ivDelete.isEnabled = it.toInt() > 1
                    ivAdd.isEnabled = it.toInt() <= skuItemBean!!.stock
                }
            }
            val commoditySpecAdapter = CommoditySpecAdapter()
            rvList.addItemDecoration(SpaceItemDecoration(5.dp))
            rvList.layoutManager = FlowLayoutManager()
            rvList.adapter = commoditySpecAdapter
            commoditySpecAdapter.setNewInstance(skuList)

            commoditySpecAdapter.setOnItemClickListener { adapter, view, position ->
                val bean = commoditySpecAdapter.data
                bean.forEach {
                    it.isSelected = false
                }
                bean[position].isSelected = true
                skuItemBean=bean[position]
                loadSkuInfo(skuItemBean!!)
                commoditySpecAdapter.notifyDataSetChanged()
            }
            findViewById<ShapeTextView>(R.id.stvBuy).setOnFastClickListener {
               if (skuItemBean!=null){
                   loge("当前选择的规格："+skuItemBean.toString())
                   var bundle = Bundle()
                   bundle.putSerializable("skuItemBean",skuItemBean)
                   bundle.putInt("itemCnt",buyCount)
                   startActivity(IntegralSubOrderActivity().javaClass,bundle)
                   delayDismiss(500)
               }else{
                   showToast("请选择规格")
               }
            }
        }

        fun loadSkuInfo(bean :IntegralSkuBean){
            ivCommodityImg?.load(bean.images, builder = {
                transform(transformRoundCorner(10))
            })
            tvCommodityName!!.text=bean.skuname

            skuprice!!.text=bean.skuprice.toString()
            price!!.text=bean.price.toString()
            stock!!.text="库存: "+bean.stock
        }

        inner class CommoditySpecAdapter : BaseQuickAdapter<IntegralSkuBean, BaseViewHolder>(R.layout.layout_commodity_specification_flow_item) {
            override fun convert(holder: BaseViewHolder, item: IntegralSkuBean) {
                val tvTag = holder.getView<TextView>(R.id.tvTag)
                tvTag.text = item.skuname
                tvTag.isSelected = item.isSelected
            }
        }
    }

    inner class ListPicAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.layout_img_item) {
        override fun convert(holder: BaseViewHolder, item: String) {
            GlideUtil.ImageLoad(this.context,item,holder.getView(R.id.image))
        }
    }
}